package com.lsy.poi.row.validator;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;

import com.lsy.poi.exception.ParseException;
import com.lsy.poi.exception.row.UniqueKeyConflictException;

/**
 * 验证：多个 row 之间，主键值 的 唯一性
 *
 */
public class UniqueValidator extends RowValidator {
	
	
	private final static String DELIMITER1 = "-";
	private final static String DELIMITER2 = "-";
	
	
	/** 指明了 选取 哪些字段 作为主键 */
	private int[] keyIndexs;
	
	/** 主键的 中文名 */
	private String keyName;
	
	/** 存储主键 */
	private Map<String, String> map;


	public UniqueValidator(Map<String, String> map, int[] keyIndexs, String[] keyNames) {
		super();
		this.map = map;
		this.keyIndexs = keyIndexs;
		this.keyName = StringUtils.join(keyNames, DELIMITER2);
	}


	@Override
	public void doValidate(Object[] cellValues, XSSFRow row) throws ParseException  {
		
		String currentKey = row.getSheet().getSheetName() + "→" + row.getRowNum();
		
		//System.out.println("@@@@@@@@@@ 开始" + currentKey);
		
		//1、从 当前 row 中，抽取出 主键
		String[] keyEles = new String[keyIndexs.length];
		int index = 0;
		for (int keyIndex : keyIndexs) {
			keyEles[index] = String.valueOf(cellValues[keyIndex]);
			index++;
		}
		
		String uniqueValue = StringUtils.join(keyEles, DELIMITER1);
		
		//2、主键 比对
		for (Entry<String, String> entry : map.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			
			boolean isEqual = uniqueValue.equals(value);
			
			if(isEqual) {
				throw new UniqueKeyConflictException(row, currentKey, key, keyName, uniqueValue);
			}
			
		}
		
		map.put(currentKey, uniqueValue);
		
		//System.out.println("@@@@@@@@@@ 结束" + currentKey);
		
	}


}
